<template>
	<view>
		<ywkefu></ywkefu>
		
		<view class="header" id="header">
			<view class="search">
				<u-search :show-action="false" v-model="params.keyword" action-text="搜索"
					placeholder="输入商品名称搜索云库" :animation="true" margin="20rpx"
					showAction="true" maxlength="30" @click="searchGoodsName()" @clickIcon="searchGoodsName()"
					@search="searchGoodsName()" @custom="searchGoodsName()"></u-search>
					<u-icon name="scan" size="28" @click="qRCodeAdd(2)"></u-icon>
			</view>
			<view>
				<u-tabs @change="tabs()" lineColor="rgb(96,114,255)" :list="list1" lineHeight="5" lineWidth="30"
					:scrollable="false"></u-tabs>
			</view>
		</view>
		
		<scroll-view :style="{ height: height + 'px' }" scroll-y="true" :scroll-with-animation="true"
			:enable-back-to-top="true" @scrolltolower="reachBottom">
			<view class="content">
				
				<u-form  v-if="type == 1" :model="form" ref="uForm" :labelStyle="{fontSize: '28rpx', color: 'rgba(0, 0, 0, 0.8)'}">
					<view class="form-edit">
						<u-form-item label="基础信息" borderBottom label-width="70">
							<view class="form-info" @click="cleanUp">
								<u--image
									:src="staticFileUrl+'/image/pages-vending-machine/goods/addGoods/empty.svg'" width="21rpx" height="21rpx">
								</u--image>
								<text>清空信息</text>
							</view>
						</u-form-item>
						<u-form-item label="商品名称" borderBottom label-width="70" required>
							<u--input v-model="form.name" @input="changName()" inputAlign="right"  placeholder="请输入商品名称" border="none"
								maxlength="30"></u--input>
						</u-form-item>
						<u-form-item label="商品分组" label-width="70" borderBottom  @click="routing">
							<view style="display: flex;align-items: center;">
								<u--input  v-model="form.commodityGroup.name"  disabled inputAlign="right"
									disabledColor="#ffffff" placeholder="请选择" border="none"></u--input>
								<view class="u-p-l-10">
									<u-icon slot="right" name="arrow-right"></u-icon>
								</view>
							</view>
						</u-form-item>
						<u-form-item label="条形码" label-width="70" borderBottom>
							<view style="display: flex;align-items: center;">
								<u--input v-model="form.barCode" type="number" inputAlign="right"  placeholder="保存时自动分配"
									border="none" maxlength="20"></u--input>
								<view class="u-p-l-10" @click="qRCodeAdd(1)">
									<u-icon name="scan"  size="24" class="scan"></u-icon>
								</view>
							</view>
						</u-form-item>
						<u-form-item label="参考售价" label-width="70" borderBottom required>
							<u--input v-model="form.retailPrice"  placeholder="请输入参考售价" inputAlign="right" maxlength="10" type="digit" border="none" @input="checkRetailPrice"></u--input>
								<text class="u-m-l-20" slot="right">元</text>
						</u-form-item>
						<u-form-item label="成本价" label-width="70" borderBottom required>
							<u--input v-model="form.costPrice" maxlength="10" placeholder="请输入成本价" inputAlign="right" type="digit" border="none" @input="checkCostPrice"></u--input>
								<text class="u-m-l-20" slot="right">元</text>
						</u-form-item>
						<u-form-item label="图片" label-width="70" required>
							<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deleteByFileNameToFTP"
								name="1" multiple :maxCount="1" :previewFullImage="true"></u-upload>
						</u-form-item>
						<u-form-item label="商品详细图" label-width="70" required>
							<u-upload :fileList="fileList2" @afterRead="afterRead2" @delete="deleteByFileNameToFTP2"
								name="2" multiple :maxCount="1" :previewFullImage="true"></u-upload>
						</u-form-item>
					</view>
				</u-form>
				
				<view v-else-if="type == 2">
					<view v-if="goodsList.length > 0">
						<view class="item-box" v-for="(item, index) in goodsList" :key="index" @click="selected(item)">
							<view class="flex">
								<view style="height: 140rpx">
									<u--image v-if="item.fileName != null && item.fileName != ''"
										:showLoading="true" :src="imgURL + item.fileName" width="150rpx"
										height="150rpx">
									</u--image>
									<u--image v-else-if="item.barCode != null && item.barCode != ''"
										:showLoading="true" :src="staticFileUrl+'/image/commodity-common/' + item.barCode+'.jpg'" width="150rpx"
										height="150rpx">
									</u--image>
								</view>
								<view class="gift-container">
									<view class="gift-box text-30">
										<text  style="display: flex;flex-wrap: wrap;">{{item.name}}</text>
									</view>
									<view class="gift-box text-20">
										<text>条形码：{{item.barCode}}</text>
									</view>
									<view class="gift-box text-price">
										<!-- <text>￥{{item.price}}</text> -->
									</view>
								</view>
							</view>
						</view>
						<u-loadmore  :status="status" :load-text="loadText" style="padding: 30rpx;"/>
					</view>
					
					<view v-else-if="goodsList.length <= 0">
						<u-empty
							text="暂无商品"
							textSize="32rpx"
							mode="data"
							textColor="rgb(34, 34, 34)"
							icon="http://cdn.uviewui.com/uview/empty/data.png"
						/>
						<view class="button-text">
							<text >您还没添加过商品，快来清加一个吧</text>
							<view class="u-m-t-59">
								<u-button   icon="plus" iconColor="rgb(255, 255, 255)" shape="circle" color="rgb(96,114,255)" text="添加商品" @click="navAddGoods()"></u-button>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<view class="footer" id="footer" v-if="type == 1">
			<view class="u-p-l-30 u-p-r-30 u-m-b-80 u-m-t-20">
				<u-button shape="circle" color="rgb(96,114,255)" :text="textName" @click="addGoods()"></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import commodityTypeEnum from '@/common/enum/commodity-type.enum.js';
	export default {
		data() {
			return {
				imgURL: this.$configPath.imgURL,
				staticFileUrl: this.$configPath.staticFileUrl,
				goodsList: [],
				params: {
					pageNum: 1,
					pageSize: 10,
					keyword: '',
					barCode:'',
				},
				status: 'loading',
				height: 0,
				currClickGoodsId: '',
				type: 1,  // 1 列表，2 查询公共参数，3 无商品 
				form: {
					name: '',
					barCode: '',
					retailPrice: '',
					// 成本价
					costPrice: '',

					fileName: '',
					commodityDetailFileName:'',
					//选中的商品分组
					commodityGroup: {},
				},
				commodityGroups: {},
				commodityTypeEnum:commodityTypeEnum,
				// 商品图片
				fileList1: [],
				fileList2: [],
				textName: '添加商品',
				loadText: {
					loadmore: '轻轻上拉加载',
					loading: '稍等一会,正在努力为您加载...',
					nomore: '没有更多了'
				},
			};
		},
		onReady() {
			this.getPomHeight();
		},
		onLoad(option) {
			if (option.barCode != null) {
				this.type = 2;
				this.params.barCode = option.barCode;
				this.findCommodityInfoCommon();
			}
			if(option.commodityId != null){
				this.textName = "确定编辑"
				this.findCommodityById(option.commodityId);
			}else{
				this.textName = "确定添加"
				this.findDefaultCommodityGroup();
			}
			// 标题
			// wx.setNavigationBarTitle({
			//      title:this.textName
			// })


		},
		watch: {
			'commodityGroups': {
				handler(newVal, oldVal) {
					console.log(newVal)
					this.form.commodityGroup = newVal;
				},
				deep: true, // 开启对象深度监听
			}
		},
		methods: {
      changName(e) {
        e = e.replace(/[^\u4E00-\u9FA5|\d|\a-zA-Z|\r\n\s,.?!，。？！…—&$=()-+/*{}[\]]/g, '')
        //重新赋值给input
        this.$nextTick(() => {
          this.form.name= e;
        });
      },
      // 查询公共商品
			findCommodityInfoCommon() {
				this.$api('commodityInfoCommon.findCommodityInfoCommon', this.params)
					.then(res => {
						console.log(res);
						if (res.status == 0) {
							this.pages = res.data.pages;
							this.status = res.data.list.length === 10 ? 'loadmore' : 'nomore';
							this.goodsList = [...this.goodsList, ...res.data.list]; //合并数组
							console.log(this.goodsList.length)
						} else {
							this.$helpers.toast('请求数据失败:' + res.msg);
						}
					})
			},
			
			//加载更多
			reachBottom() {
				if (this.status == 'nomore') {
					return;
				}
				this.status = 'loading';
				this.params.pageNum++;
				this.findCommodityInfoCommon();
			},
			
			
			findDefaultCommodityGroup() {
				const param = {
					type: this.commodityTypeEnum.GENERAL_GOODS
				}
				this.$api('commodityGroup.getDefaultCommodityGroup', param).then(res => {
					if (res.status == 0) {
						if (!this.$u.test.isEmpty(res.data)) {
							this.form.commodityGroup = res.data
						}
					} else {
						getApp().err('加载默认分组不成功:' + res.msg);
					}
				})
			},
			
			findCommodityById(id) {
				let body ={
					id:id
				}
				this.$api('commodity.findCommodityById', body).then(res => {
					if (res.status == 0) {
						if (!this.$u.test.isEmpty(res.data)) {
							this.form = res.data
							if (this.form.fileName) {
								this.fileList1.push({
									url: this.$configPath.imgURL + '/' + this.form.fileName
								});
							}
							if (this.form.commodityDetailFileName) {
								this.fileList2.push({
									url: this.$configPath.imgURL + '/' + this.form.commodityDetailFileName
								});
							}
						}
					} else {
						getApp().err('加载默认分组不成功:' + res.msg);
					}
				})
			},
			
			routing() {
				let id = uni.$u.test.isEmpty(this.form.commodityGroup) ? '' : this.form.commodityGroup.id;
				uni.navigateTo({
					url: '/pages-commodity/commodity-group?type=' + this.commodityTypeEnum.GENERAL_GOODS +
						'&id=' + id
				});
			},
			
			// 调启扫一扫
			qRCodeAdd(type) {
				uni.showLoading({
					title: "正在调起...",
					mask: true
				})
				var that = this;
				uni.scanCode({
					success: function(res) {
						uni.hideLoading();
						if(type == 2){
							console.log(that)
							that.goodsList = [];
							that.params.pageNum = 1;
							that.params.barCode = res.result;
							that.findCommodityInfoCommon();
							that.type = type;
							
						}else{
							that.form.barCode = res.result;
						}
					},
					fail(res) {
						console.log(res);
						uni.hideLoading();
					}
				});
			},
			
			selected(item){
				this.fileList1 = [];
				this.form.name = item.name;
				this.form.barCode = item.barCode;
				this.fileList1.push({
					url: this.staticFileUrl+'/image/commodity-common/' + item.barCode+'.jpg'
				});
				this.type = 1;
			},

			cleanUp(){
        this.form.name='';
        this.form.barCode='';
        this.form.retailPrice='';
        this.form.costPrice='';
        this.form.fileName='';
			},
			  async afterRead(event) {
			        uni.showLoading({
			          title: '上传中',
			          mask: true
			        })
			        const item = {
			          url: event.file[0].url,
			          status: 'uploading',
			          message: '上传中'
			        }
			        this.fileList1.push(item);
					  uni.compressImage({
						src: event.file[0].url,
						  quality: 30, // 越小质量越不好，但压缩率就更高
						  success: async res => {
							  this.uploadFilePromise(res.tempFilePath,1).then((result) => {
								  this.form.fileName = result;
								  this.fileList1.splice(0, 1, Object.assign(item, {
									  status: 'success',
									  message: '',
									  url: event.file[0].url
								  }))
							  }).catch((err) => {
								  console.error("bankCardACatch", err)
								  this.fileList1.splice(0, 1);
							  })
						  }
					  })
			},
			async afterRead2(event) {
			        uni.showLoading({
			          title: '上传中',
			          mask: true
			        })
			        const item = {
			          url: event.file[0].url,
			          status: 'uploading',
			          message: '上传中'
			        }
			        this.fileList2.push(item);
					  uni.compressImage({
						src: event.file[0].url,
						  quality: 30, // 越小质量越不好，但压缩率就更高
						  success: async res => {
							  this.uploadFilePromise(res.tempFilePath,2).then((result) => {
								  this.form.commodityDetailFileName = result;
								  this.fileList2.splice(0, 1, Object.assign(item, {
									  status: 'success',
									  message: '',
									  url: event.file[0].url
								  }))
							  }).catch((err) => {
								  console.error("bankCardACatch", err)
								  this.fileList2.splice(0, 1);
							  })
						  }
					  })
			},
			uploadFilePromise(fileUrl,type) {
				console.log(fileUrl)
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: this.$configPath.baseURL + '/api/upload/uploadImageToFTP',
						filePath: fileUrl,
						name: 'image',
						header: {
							Authorization: 'Bearer ' + this.$store.getters.GET_VALUE("GET_TOKEN")
						},
						/* 会与全局header合并，如有同名属性，局部覆盖全局 */
						timeout: 6000,
						formData: {
							user: 'test'
						},
						success: (res) => {
							let data = JSON.parse(res.data);
							if (data.status == 0) {
								setTimeout(() => {
									resolve(data.data.keyRes);
									this.$helpers.toast("上传成功");
								}, 1000)
							} else {
								if (uni.$u.test.isEmpty(data.msg)) {
									this.$helpers.toast("图片上传失败");
								} else {
									this.$helpers.toast(data.msg);
								}
								if(type == 1){
									this.deleteByFileNameToFTP();
								}else{
									this.deleteByFileNameToFTP2();
								}
								
							}
						},
						fail: (res) => {
							let errMsg = res.errMsg;
							if (uni.$u.test.contains(errMsg, 'timeout')) {
								errMsg = "请求超时，请重新上传";
							}
							if(type == 1){
								this.deleteByFileNameToFTP();
							}else{
								this.deleteByFileNameToFTP2();
							}
							this.$helpers.toast(errMsg);
						},
					});
				})
			},
			
			
			// 将公共的图片上传到私有的图片库上
			uploadFile(){
				return new Promise((resolve, reject) => {
					 uni.downloadFile({
						url: this.fileList1[0].url, //仅为示例，并非真实的资源
						success: async (res) => {
							if (res.statusCode === 200) {
								 uni.compressImage({
									src: res.tempFilePath,
									  quality: 60, // 越小质量越不好，但压缩率就更高
									  success: async res2 => {
										 this.uploadFilePromise(res2.tempFilePath,1).then((result) => {
											  this.form.fileName = result;
											  resolve();
										 })
									  }
								})
							}
						}
					});
				})
			},
			
			// 删除已上传的图片
			deleteByFileNameToFTP() {
				this.form.fileName = '';
				this.fileList1 = [];
				this.$helpers.toast("删除成功");
			},
			// 删除已上传的图片
			deleteByFileNameToFTP2() {
				this.form.commodityDetailFileName = '';
				this.fileList2 = [];
				this.$helpers.toast("删除成功");
			},

			//清除关键字
			clearKeyword() {
				this.params.keyword = '';
			},
			//关键字搜索
			searchGoodsName() {
				this.params.barCode = '';
				this.type = 2;
				this.goodsList = [];
				this.findCommodityInfoCommon();
			},

			async addGoods(){
				if (this.form.name == null || this.form.name.length == 0) {
					this.$helpers.toast('商品名称不能为空');
					return;
				}
				if (this.form.costPrice == null || this.form.costPrice <= 0) {
					this.$helpers.toast('请输入成本价');
					return;
				}
				if (this.form.retailPrice == null || this.form.retailPrice <= 0) {
					this.$helpers.toast('请输入参考售价');
					return;
				}
				if ((this.form.retailPrice * 1) <= (this.form.costPrice * 1)) {
					this.$helpers.toast('参考售价需要大于成本价');
					return;
				}
				if (this.form.fileName == null || this.form.fileName.length == 0) {
					if(this.fileList1.length >0 && this.fileList1[0].url != '' &&  this.fileList1[0].url != null){
						await this.uploadFile();
					}else{
						this.$helpers.toast('请上传商品图片');
						return;
					}
				}
				uni.showLoading({
					title: '请求中',
					mask: true
				})
				
	
				this.$api('commodity.editVendingMachineGoods', this.form)
					.then(res => {
						if (res.status == 0) {
							this.$helpers.toast('添加成功');
							setTimeout(() => {
								uni.navigateBack({
									delta: 1
								})
							}, 800)
						} else {
							this.$helpers.toast('添加失败:' + res.msg);
						}
				})
			},
			//进入新增商品页面
			navAddGoods() {
				this.type = 1;
			},

			checkCostPrice(e) {
				if (e == '.'){
					this.$helpers.toast('请输入以数字开头的成本价');
					this.$nextTick(() => {
						this.form.costPrice = null;
					});
					return
				}
			
				//正则表达试
				e = (e.match(/^\d*(\.?\d{0,2})/g)[0]) || null
				//重新赋值给input
				this.$nextTick(() => {
					this.form.costPrice = e
				})
			},
			
			checkRetailPrice(e) {
				if (e == '.'){
					this.$helpers.toast('请输入以数字开头的零售价');
					this.$nextTick(() => {
						this.form.retailPrice = null;
					});
					return
				}
			
				//正则表达试
				e = (e.match(/^\d*(\.?\d{0,2})/g)[0]) || null
				//重新赋值给input
				this.$nextTick(() => {
					this.form.retailPrice = e
				})
			},
			
			
			
			
			// 获取各个盒子的高度
			getPomHeight() {
				let query = wx.createSelectorQuery().in(this)
				query.select('#header').boundingClientRect()
				if(this.type == 1){
					query.select('#footer').boundingClientRect()
				}
				query.exec(res => {
					let windowHeight = wx.getSystemInfoSync().windowHeight
					this.height = windowHeight
					for (let i = 0; i < res.length; i++) {
						this.height -= res[i].height;
						
					}
				})
			
			},
		}
	};
</script>

<style lang="scss">
	page {
		background: rgb(255, 255, 255);
	}
	
	 /deep/ .u-button__text{
	      padding-left: 10rpx;
	}
  /deep/ .u-form-item__body {
    padding: 36rpx 0 !important;
  }
	.header {
		background-color: #FFFFFF;
	
		.search {
			display: flex;
			justify-content: space-between;
			align-items: center;
      padding: 20rpx 20rpx 0;
		}
	}

	.content {
		.form-edit{
			margin: 0 30rpx;
			border-radius: 16rpx;
			background-color: #FFFFFF;
			.form-info{
				display: flex;
				align-items: center;
				justify-content: flex-end;
				text{
					color: #6072FF;
					font-size: 24rpx;
				}
			}
		}
		
		.button-text{
			padding: 40rpx 215rpx;
			color: rgba(34, 34, 34, 0.6);
			text-align: center;
			font-size: 20rpx;
			.name-text{
				margin-bottom: 10rpx;
			}
		}

	}

	.footer {
		width: 100%;
		background-color: white;
		position: fixed;
		bottom: 0rpx;
		z-index: 100;
	}

	.item-box {
		margin: 0 24rpx;
		display: flex;
		justify-content: space-between;
		border-radius: 16rpx;
		background-color: rgb(255, 255, 255);
		padding: 30rpx;
		
		.flex {
			width: 100%;
			display: flex;
			.gift-container {
				width: 100%;
				margin-left: 20rpx;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				
				.gift-box {
					display: flex;
					justify-content: space-between;
				}
			
				.salesVolume{
					margin-left: 20rpx;
				}
			
			}
		}
		
	}
	.text-30 {
		color: rgb(34, 34, 34);
		font-size: 30rpx;
		margin-bottom: 13rpx;
	}
	.text-price {
		color: rgb(255, 0, 0);
		font-size: 24rpx;
	}
	.text-20 {
		color: rgba(34, 34, 34, 0.6);
		font-size: 20rpx;
	}
</style>
